package com.zqwh.xtool.model.offline;

import android.content.Context;

import com.zqwh.yj.sdk.utils.CommonUtils;
import com.zqwh.yj.sdk.utils.httpRequest.subscribers.NetCallback;
import com.zqwh.xtool.api.offline.LendOrderDetailResposity;
import com.zqwh.xtool.api.offline.LendOrderResposity;
import com.zqwh.xtool.api.offline.StockResposity;
import com.zqwh.xtool.converter.LendOrderDetail2StockVOConverter;
import com.zqwh.xtool.domain.LendInfo;
import com.zqwh.xtool.domain.LentData;
import com.zqwh.xtool.domain.StockVO;
import com.zqwh.xtool.greendao.db.LendOrder;
import com.zqwh.xtool.greendao.db.LendOrderDetail;
import com.zqwh.xtool.greendao.db.Stock;
import com.zqwh.xtool.model.LendOrderModel;
import com.zqwh.xtool.utils.ZqwhUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

public class LendOrderModelOfflineImpl implements LendOrderModel {
    private Context context;
    private StockResposity stockResposity;
    private LendOrderResposity lendOrderResposity;
    private LendOrderDetailResposity lendOrderDetailResposity;

    public LendOrderModelOfflineImpl(Context context) {
        this.context = context;
        this.stockResposity = new StockResposity(this.context);
        this.lendOrderResposity = new LendOrderResposity(this.context);
        this.lendOrderDetailResposity = new LendOrderDetailResposity(this.context);
    }

    @Override
    public void getOwingStock(Long devId, Long userId, NetCallback<LentData> callback) {

    }

    @Override
    public void getPreSubmitInfo(Long devId, Long userId, String epcs, NetCallback<LendInfo> callback) {

    }

    @Override
    public void submitLendReturnOrder(Long devId, Long userId, String epcs, NetCallback<Object> callback) {

    }

    @Override
    public void submitLendOrder(Long devId, Long userId, String orderNo, String stockIds, NetCallback<Object> callback) {
        boolean flag = true;

        List<LendOrderDetail> lendOrderDetailList = new ArrayList<>();
        String lentToolsInfo = "";
        List<String> stockIdList = CommonUtils.stringToList(stockIds, ",");
        List<Stock> stockList = stockResposity.queryStockListByStockIdIn(stockIdList);
        String lendOrderId = ZqwhUtils.genKey(devId);
        LendOrder lendOrder = new LendOrder();
        lendOrder.setLendOrderId(lendOrderId);
        lendOrder.setUserId(userId);
        lendOrder.setValid(true);
        lendOrder.setRentStatus("UN_RETURN");
        lendOrder.setDevId(devId);
        lendOrder.setOrderNo(orderNo);
        lendOrder.setLentToolsInfo("");
        lendOrder.setTotalNum(0);
        lendOrder.setReturnedNum(0);
        lendOrder.setUpdated(true);
        lendOrder.setValid(true);

        for (Stock stock : stockList){

            stock.setHasLent(true);
            stock.setUpdated(true);
            stock.setValid(true);
            stock.setUpdateTime(new Date(System.currentTimeMillis()));

            LendOrderDetail lendOrderDetail = new LendOrderDetail();
            lendOrderDetail.setLendOrderDetailId(ZqwhUtils.genKey(devId));
            lendOrderDetail.setUserId(userId);
            lendOrderDetail.setToolCategoryId(stock.getToolCategoryId());
            lendOrderDetail.setToolCategoryName(stock.getToolCategoryName());
            lendOrderDetail.setToolDesc(stock.getToolDesc());
            lendOrderDetail.setToolId(stock.getToolId());
            lendOrderDetail.setToolName(stock.getToolName());
            lendOrderDetail.setToolImage(stock.getToolImage());
            lendOrderDetail.setToolSpec(stock.getToolSpec());
            lendOrderDetail.setEpc(stock.getEpc());
            lendOrderDetail.setDevId(devId);
            lendOrderDetail.setStockId(stock.getStockId());
            lendOrderDetail.setLendOrderId(lendOrderId);
            lendOrderDetail.setRentStatus("UN_RETURN");
            lendOrderDetail.setValid(true);
            lendOrderDetail.setUpdated(true);
            lendOrderDetail.setCreateTime(new Date(System.currentTimeMillis()));
            lendOrderDetailList.add(lendOrderDetail);
            if (Objects.equals(lentToolsInfo, "")) {
                lentToolsInfo = stock.getToolName();
            }else {
                lentToolsInfo = lentToolsInfo+","+stock.getToolName();
            }
        }
        lendOrder.setLentToolsInfo(lentToolsInfo);
        lendOrder.setTotalNum(stockList.size());
        lendOrder.setReturnedNum(0);

        if (!lendOrderResposity.insertLendOrder(lendOrder)){
            flag = false;
        }
        if (!lendOrderDetailResposity.insertMultLendOrderDetail(lendOrderDetailList)){
            flag = false;
        }
        if (!stockResposity.insertMultStock(stockList)){
            flag = false;
        }

        if (flag){
            callback.onSuccess(null);
        }else {
            callback.onSuccess("提交失败");
        }
    }

    @Override
    public void submitReturnOrder(Long devId, Long userId, String stockIds, NetCallback<Object> callback) {
        boolean flag = true;
        List<String> stockIdList = CommonUtils.stringToList(stockIds, ",");
        List<LendOrder> lendOrderList = new ArrayList<>();
        List<LendOrderDetail> detailList = lendOrderDetailResposity.queryLendOrderDetailList(userId, devId, "UN_RETURN", stockIdList);
        List<Stock> stockList = stockResposity.queryStockListByStockIdIn(stockIdList);
        final Date NOW = new Date();
        for (LendOrderDetail d: detailList){
            // detail 设置归还
            d.setRentStatus("RETURNED");
            d.setReturnDate(NOW);
            d.setUpdated(true);
            long timeDelta = NOW.getTime() - d.getCreateTime().getTime();
            long days = TimeUnit.MILLISECONDS.toDays(timeDelta);
            long hours = TimeUnit.MILLISECONDS.toHours(timeDelta%TimeUnit.DAYS.toMillis(1));
            long minutes = TimeUnit.MILLISECONDS.toMinutes(timeDelta%TimeUnit.HOURS.toMillis(1));
            long seconds = TimeUnit.MILLISECONDS.toSeconds(timeDelta%TimeUnit.MINUTES.toMillis(1));
            d.setRentDuration(days+"天"+hours+"小时"+minutes+"分"+seconds+"秒");

            LendOrder lendOrder = lendOrderResposity.queryLendOrderById(d.getLendOrderId());
            lendOrder.setUpdated(true);
            lendOrder.setReturnedNum(lendOrder.getReturnedNum() + 1);
            if (lendOrder.getTotalNum() > lendOrder.getReturnedNum()) {
                lendOrder.setRentStatus("PART_RETURN");
            } else {
                lendOrder.setRentStatus("RETURNED");
                lendOrder.setFinishTime(NOW);
            }
            lendOrderList.add(lendOrder);
        }

        // 库存设置
        for (Stock stock:stockList){
            stock.setHasLent(false);
            stock.setUpdated(true);
        }
        if (!lendOrderResposity.insertMultLendOrder(lendOrderList)){
            flag = false;
        }
        if (!lendOrderDetailResposity.insertMultLendOrderDetail(detailList)){
            flag = false;
        }
        if (!stockResposity.insertMultStock(stockList)){
            flag = false;
        }
        if (flag){
            callback.onSuccess(null);
        }else {
            callback.onSuccess("提交失败");
        }
    }

    @Override
    public void getLentOrderDetailList(Long devId, Long userId, NetCallback<HashMap<String, List<StockVO>>> callback) {
        List<LendOrderDetail> rfidStockList = lendOrderDetailResposity.queryLendOrderDetailList(userId, devId, "UN_RETURN", true);
        List<LendOrderDetail> noRfidStockList = lendOrderDetailResposity.queryLendOrderDetailList(userId, devId, "UN_RETURN", false);
        HashMap<String, List<StockVO>> stockMap = new HashMap<>();
        stockMap.put("rfid_stock", LendOrderDetail2StockVOConverter.convert(rfidStockList));
        stockMap.put("no_rfid_stock", LendOrderDetail2StockVOConverter.convert(noRfidStockList));
        callback.onSuccess(stockMap);
    }

    @Override
    public boolean insertMultLendOrder(List<LendOrder> lendOrderList) {
        return lendOrderResposity.insertMultLendOrder(lendOrderList);
    }

    @Override
    public boolean insertMultLendOrderDetail(List<LendOrderDetail> lendOrderDetailList) {
        return lendOrderDetailResposity.insertMultLendOrderDetail(lendOrderDetailList);
    }
}
